import { promises as fs } from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';

/**
 * Generates a random secret for JWT authentication
 */
function generateAuthSecret(): string {
  return crypto.randomBytes(32).toString('hex');
}

/**
 * Creates a .env file with PGlite configuration
 */
async function setupPGlite() {
  console.log('Setting up PGlite environment...');
  
  // 确保数据目录存在
  const dataDir = path.join(process.cwd(), 'data');
  try {
    await fs.mkdir(dataDir, { recursive: true });
    console.log(`Created data directory at: ${dataDir}`);
  } catch (err) {
    console.log(`Data directory already exists at: ${dataDir}`);
  }
  
  // Define environment variables
  const envVars = {
    POSTGRES_URL: 'pglite://./data/pglite.db',
    STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY || '',
    STRIPE_WEBHOOK_SECRET: process.env.STRIPE_WEBHOOK_SECRET || '',
    BASE_URL: 'http://localhost:3000',
    AUTH_SECRET: generateAuthSecret(),
  };
  
  // Create .env file content
  const envContent = Object.entries(envVars)
    .map(([key, value]) => `${key}=${value}`)
    .join('\n');
  
  // Write .env file
  await fs.writeFile(path.join(process.cwd(), '.env'), envContent);
  console.log('.env file created with PGlite file-based configuration.');
  
  console.log('\nNext steps:');
  console.log('1. Run migrations: pnpm db:migrate');
  console.log('2. Seed the database: pnpm db:seed');
  console.log('3. Start the development server: pnpm dev');
}

// Run the setup
setupPGlite().catch(console.error); 